package com.source.multithread.xml;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Author wengqy
 * @Date 2021/1/7
 */
public class XMLUtils {
    private static final Logger log = LoggerFactory.getLogger(XMLUtils.class);
    private static final String NAMESPACE = " xmlns=\"http://www.bankofshanghai.com/BOSFX/2010/08\"";
    private static final String BOSFXII = "BOSFXII" ;
    private static  final String ERROR = "转换报文发生异常";
    public XMLUtils(){}

    public static  String toXML(Student obj){
        StringWriter sw = new StringWriter();
        JAXBContext context;
        Marshaller marshaller;

        try {
            context = JAXBContext.newInstance(Student.class);
            marshaller = context.createMarshaller();
            marshaller.marshal(obj,sw);
        }catch (JAXBException e){
            log.error("对象转为xmlString出错", e);
        }

        return sw.toString();
    }

    public static Object toObject(String xml, Class<?> clazz){
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(false);
        try{
            XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
            StringReader sr = new StringReader(xml);
            Source source = new SAXSource(xmlReader, new InputSource(sr));
            return JAXBContext.newInstance(clazz).createUnmarshaller().unmarshal(source);
        }catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }
}
